<?php
declare(strict_types=1);

namespace app\middleware;

use app\common\service\JwtService;
use think\facade\Request;
use Closure;
use think\Response;

class JwtAuth
{
    public function handle($request, Closure $next)
    {
        try {
            // 获取令牌
            $token = $this->getTokenFromRequest($request);
            
            // 验证令牌
            $payload = app(JwtService::class)->verifyToken($token);
            
            // 注入用户信息
            $request->user = [
                'user_id' => $payload['sub'],
                'claims'  => $payload['claims']
            ];

            return $next($request);

        } catch (\Exception $e) {
            return json([
                'code' => 401,
                'msg'  => $e->getMessage()
            ], 401);
        }
    }

    /**
     * 从请求中获取令牌
     */
    protected function getTokenFromRequest($request): string
    {
        $token = $request->header('Authorization', '');
        if (empty($token)) {
            throw new \Exception('缺少认证令牌', 401);
        }

        if (preg_match('/Bearer\s+(\S+)/', $token, $matches)) {
            return $matches[1];
        }

        throw new \Exception('令牌格式错误', 401);
    }
}
